<template>
  <div class="flex flex-col h-full">
    <a-card>
      <div class="flex justify-between items-center">
        <a-button type="primary" class="mr-4" @click="router.go(-1)"> 返回 </a-button>
        <a-descriptions class="mt-3" :column="4">
          <a-descriptions-item label="单号" class="w-1/2"> {{ formState?.ckdh || '-' }}</a-descriptions-item>
          <a-descriptions-item label="出库仓库" class="w-1/2"> {{ formState?.ckmc || '-' }}</a-descriptions-item>
          <a-descriptions-item label="去向" class="w-1/2"> {{ formState?.qx || '-' }}</a-descriptions-item>
          <a-descriptions-item label="制单人" class="w-1/2"> {{ formState?.jbrname || '-' }}</a-descriptions-item>
          <a-descriptions-item label="制单时间" class="w-1/2"> {{ formState?.addtime || '-' }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-card>
    <a-card class="mt-2 flex-1">
      <BaseTable :data-source="dataSource" column-code="000148" max-fill :extra-height="64" :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')">
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'cklb'">
            <EditCell title="类别">
              <SelectItem
                v-model:value="record.cklbmc"
                type="DT00290"
                trigger="focus"
                placeholder="请选择"
                @blur="onInputfocus(record)"
                @select="selectDict($event, record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'mc'">
            <EditCell title="物品名称">
              <SelectMedicine
                :value="{ mc: record.mc, gg: record.gg, cj: record.cj }"
                type="视光仓储物资"
                :search-params="{ ckbh: formState?.ckckbh, lx: 0 }"
                @select="onSelectMedicine($event, record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'sl'">
            <EditCell title="出库数量">
              <BaseInput
                v-model:value="record.sl"
                v-input:int
                class="text-right"
                :auto-focus="focusCell === record.key"
                :suffix="record.sfxm?.dw"
                placeholder="请输入"
                @blur="onInputfocus(record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'cmemo'">
            <EditCell title="备注">
              <a-input v-model:value="record.cmemo" :suffix="record.sfxm?.dw" placeholder="请输入" @blur="onInputfocus(record)" />
            </EditCell>
          </template>

          <template v-if="column.dataIndex === 'action'">
            <ConfirmModal @confirm="onDel(record)">
              <a-button type="text" danger size="small">删除</a-button>
            </ConfirmModal>
          </template>
        </template>
        <template #footer>
          <div class="text-center sticky bottom-0">
            <a-button class="mr-2" type="primary" ghost @click="addRow()"> 新增一行 </a-button>
            <a-button type="primary" @click="saveNewRows()"> 保存 </a-button>
          </div>
        </template>
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import BaseTable from '@/components/BaseTable'
import { post } from '@/utils/request'
import EditCell from '@/components/EditCell'
import useUserStore from '@/store/user'
import ConfirmModal from '@/components/ConfirmModal'

const { empId } = useUserStore()
const route = useRoute()
const router = useRouter()
const formState = ref({})
const loading = ref(false)
const focusCell = ref('')
const dataSource = ref([])
// const defaultRow = {
//   isNew: true,
//   key: '',
//   ypbh: '',
//   sl: '',
//   cmemo: ''
// }
const onInputfocus = (res) => {
  if (res.sl <= 0) return message.error('出库数量不可小于0')
  editRow(res)
}
const getMainData = async () => {
  const { data, code } = await post('/oos/psiform/getOutBoundHeadList', {
    dhmc: route.query.ckdh || ''
  })
  if (code === 0) {
    formState.value = data[0]
  }
}
const onDel = async (record) => {
  if (record.ckdh) {
    const res = await post('/oos/psiform/doDeleteOutBoundDetail', { dh: route.query.ckdh || '', lsh: record.ckmxlsh })
    if (res.code !== 0) {
      message.error(res.msg)
      return
    }
    message.success(res.msg)
    dataSource.value = dataSource.value.filter((item) => item.key !== record.key)
  } else {
    dataSource.value = dataSource.value.filter((item) => item.key !== record.key)
    message.success('删除成功')
  }
}

const editRow = (row) => !row.isNew && fetchSave(row)
const fetchSave = async (row, callBack) => {
  if (row.sl > Math.abs(parseInt(row.dqkc))) {
    dataSource.value = dataSource.value.map((item) => {
      if (row?.lsh) {
        if (item.lsh === row.lsh) {
          item.sl = ''
        }
      } else {
        if (item.key === row.key) {
          item.sl = ''
        }
      }
      return item
    })
    return message.error('出库数量不可大于库存量')
  }
  row.sl = row.bslx === 1 ? -Math.abs(row.sl) : Math.abs(row.sl)
  const rows = {
    ckdh: route.query.ckdh || '',
    ...row
  }
  const { code, msg } = await post('/oos/psiform/doSaveOutBoundDetail', rows)
  if (code !== 0) return message.error(msg || '操作失败')
  message.destroy()
  message.success(row.isNew ? '新增成功' : '修改成功')
  getData()
  callBack()
}
const onSelectMedicine = (medicine, row) => {
  row.dqkc = medicine.sl
  // row.sfxmb = medicine
  row.sl = 1
  row.cj = medicine.cj
  row.ph = medicine.ph
  row.bh = medicine.ypbh
  row.yxq = medicine.yxq
  row.ypbh = medicine.ypbh
  row.gg = medicine.gg
  row.dw = medicine.dw
  row.zxdwsl = 1
  row.mc = medicine.mc
  row.czr = empId
  row.jlsl = row.zxdwsl * medicine?.jldwzsb || 0

  focusCell.value = row.key
  editRow(row)
}
//添加行
const addRow = async () => {
  const key = `row-${dataSource.value.length}`
  const addRow = { key, isNew: true, addtime: dayjs().format('YYYY-MM-DD HH:mm:ss') }
  dataSource.value.push(addRow)
}

const getData = async () => {
  loading.value = true
  const { data, code } = await post('/oos/psiform/getOutBoundDetailList', {
    ckdh: route.query.ckdh || '',
    pageNum: 1,
    pageSize: 999
  })
  loading.value = false
  if (code === 0) {
    dataSource.value = data
  }
}
const saveNewRows = async () => {
  const newRow = dataSource.value.filter((item) => item.isNew)
  for (const item of newRow) {
    if (item.ypbh && item.sl) {
      await new Promise((resolve) => {
        fetchSave(item, () => {
          resolve()
        })
      })
    } else {
      message.destroy()
      message.error('请填写完整信息')
    }
  }
  // newRow.forEach((item) => {
  //   if (item.ypbh && item.sl) {
  //     fetchSave(item)
  //   } else {
  //     message.destroy()
  //     message.error('请填写完整信息')
  //   }
  // })
}

const selectDict = (val, row) => {
  row.cklb = val
}

watchEffect(() => {
  if (route.query?.ckdh) {
    getMainData()
    getData()
  }
})
</script>
<style lang="less" scoped>
:deep(.ant-table-row-expand-icon) {
  display: none;
}
</style>
